﻿#include <iostream>

static void printOneCircle(const int* matrix, const int rowSize, const int colSize, int startX, int startY, int endX, int endY)
{
    if (startX == endX)
    {
        for (int y = startY; y <= endY; y++)
        {
            printf("%d ", matrix[startX + y * colSize]);
        }

        return;
    }

    if (startY == endY)
    {
        for (int x = startX; x <= endX; x++)
        {
            printf("%d ", matrix[x + startY * colSize]);
        }

        return;
    }

    for (int x = startX; x < endX; x++)
    {
        printf("%d ", matrix[x + startY * colSize]);
    }

    for (int y = startY; y < endY; y++)
    {
        printf("%d ", matrix[endX + y * colSize]);
    }

    for (int x = endX; x > startX; x--)
    {
        printf("%d ", matrix[x + endY * colSize]);
    }

    for (int y = endY; y > startY; y--)
    {
        printf("%d ", matrix[startX + y * colSize]);
    }
}

static void print(const int* matrix, const int rowSize, const int colSize)
{
    int startX = 0;
    int startY = 0;
    int endX = colSize - 1;
    int endY = rowSize - 1;
    while (startX <= endX && startY <= endY)
    {
        printOneCircle(matrix, rowSize, colSize, startX, startY, endX, endY);
        ++startX;
        ++startY;
        --endX;
        --endY;
    }
}

/**
 * 用螺旋的方式打印矩阵，比如如下的矩阵
 * 0  1  2  3
 * 4  5  6  7
 * 8  9 10 11
 * 打印顺序为: 0 1 2 3 7 11 10 9 8 4 5 6
 *
 * 思路:
 * 定义两个点,A(x1,y1),B(x2,y2)
 * 1. A点在左上角，B点在右下角，然后从A开始顺时针打印A和B定位的矩形的一圈元素
 * 2. A向右下方移动，B向左上方移动，然后从A开始顺时针打印A和B定位的矩形的一圈元素
 * ...
 * 3. 直到A和B的点发生交错(x1 > x2 或者 y1 > y2)，打印结束
 */
int main_Spiral()
{
    int colSize = 7;
    int matrix[] = {
        0,1,2,3,4,5,6,
        7,8,9,10,11,12,13,
        14,15,16,17,18,19,20
    };

    int rowSize = sizeof(matrix) / (sizeof(int) * colSize);
    print(matrix, rowSize, colSize);
    return 0;
}